<template>
    <div class="spatial-data-loader">
        <h3>空间数据加载</h3>
        <div class="spatial-info">
            <p><strong>说明：</strong>空间数据包括几何形体、GeoJSON、KML、3D模型、标签等</p>
            <p>支持点、线、面、体要素和复杂空间数据结构</p>
        </div>
        <div class="spatial-controls">
            <button @click="loadGeoJSON" class="spatial-btn">加载GeoJSON</button>
            <button @click="loadKML" class="spatial-btn">加载KML</button>
            <button @click="load3DModel" class="spatial-btn">加载3D模型</button>
            <button @click="addLabels" class="spatial-btn">添加标签</button>
            <button @click="createGeometry" class="spatial-btn">创建几何形体</button>
            <button @click="clearSpatialData" class="clear-btn">清除空间数据</button>
        </div>
        <div class="spatial-details">
            <p><strong>GeoJSON：</strong>JSON格式的地理数据，支持点线面要素</p>
            <p><strong>KML：</strong>Keyhole标记语言，Google Earth标准</p>
            <p><strong>3D模型：</strong>支持glTF格式的3D模型</p>
            <p><strong>标签：</strong>文本标签和图形标签</p>
        </div>
        <div class="spatial-status">
            <p>数据源状态: <span :class="dataSourceStatusClass">{{ dataSourceStatus }}</span></p>
            <p>数据源数量: <span :class="dataSourceCountClass">{{ dataSourceCount }}</span></p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;
const dataSourceStatus = ref('未加载');
const dataSourceStatusClass = ref('status-unknown');
const dataSourceCount = ref(0);
const dataSourceCountClass = ref('status-unknown');
let addedDataSources: any[] = [];

// 获取Cesium原生Viewer实例
const getCesiumViewer = () => {
    return xbsjEarthUi.activeViewer?.innerViewer?.viewer as any;
};

// 加载GeoJSON数据
const loadGeoJSON = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        return;
    }

    try {
        dataSourceStatus.value = '加载中...';
        dataSourceStatusClass.value = 'status-loading';

        // 创建示例GeoJSON数据
        const geoJSONData = {
            "type": "FeatureCollection",
            "features": [
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [116.0, 40.0]
                    },
                    "properties": {
                        "name": "突发事件",
                        "type": "事件点",
                        "description": "这是一个事件点"
                    }
                },
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "LineString",
                        "coordinates": [
                            [116.0, 40.0],
                            [121.0, 31.0],
                            [113.0, 23.0]
                        ]
                    },
                    "properties": {
                        "name": "连接线",
                        "type": "路径"
                    }
                },
                {
                    "type": "Feature",
                    "geometry": {
                        "type": "Polygon",
                        "coordinates": [[
                            [118.0, 32.0],
                            [119.0, 32.0],
                            [119.0, 33.0],
                            [118.0, 33.0],
                            [118.0, 32.0]
                        ]]
                    },
                    "properties": {
                        "name": "滁州区域",
                        "type": "区域"
                    }
                }
            ]
        };

        // 加载GeoJSON数据源
        const dataSource = (window as any).Cesium.GeoJsonDataSource.load(geoJSONData, {
            stroke: (window as any).Cesium.Color.BLUE.withAlpha(0.8),
            strokeWidth: 2.3,
            fill: (window as any).Cesium.Color.RED.withAlpha(0.3),
            clampToGround: true,
            markerSize: 20,
            markerColor: (window as any).Cesium.Color.RED,
            markerSymbol: '?'
        });

        viewer.dataSources.add(dataSource);
        addedDataSources.push(dataSource);
        dataSourceCount.value = addedDataSources.length;

        // 为Point要素添加文字标签和鼠标悬停提示
        dataSource.then((loadedDataSource: any) => {
            loadedDataSource.entities.values.forEach((entity: any) => {
                if (entity.position && entity.properties) {
                    // 为Point要素添加文字标签
                    entity.label = {
                        text: entity.properties.name.getValue(),
                        font: "14pt sans-serif",
                        fillColor: (window as any).Cesium.Color.WHITE,
                        outlineColor: (window as any).Cesium.Color.BLACK,
                        outlineWidth: 2,
                        style: (window as any).Cesium.LabelStyle.FILL_AND_OUTLINE,
                        pixelOffset: new (window as any).Cesium.Cartesian2(0, -30),
                        horizontalOrigin: (window as any).Cesium.HorizontalOrigin.CENTER,
                        verticalOrigin: (window as any).Cesium.VerticalOrigin.BOTTOM,
                        scale: 1.0,
                        showBackground: true,
                        backgroundColor: (window as any).Cesium.Color.BLACK.withAlpha(0.7),
                        backgroundPadding: new (window as any).Cesium.Cartesian2(7, 5)
                    };

                    // 设置鼠标悬停提示
                    entity.description = entity.properties.description.getValue();
                }
            });
        });

        dataSourceStatus.value = '加载成功';
        dataSourceStatusClass.value = 'status-success';
        dataSourceCountClass.value = 'status-success';

        console.log('GeoJSON数据加载成功');
    } catch (error) {
        console.error('加载GeoJSON数据失败:', error);
        dataSourceStatus.value = '加载失败';
        dataSourceStatusClass.value = 'status-error';
    }
};

// 加载KML数据
const loadKML = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        return;
    }

    try {
        dataSourceStatus.value = '加载中...';
        dataSourceStatusClass.value = 'status-loading';

        // 创建示例KML数据
        const kmlData = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
    <Document>
        <name>示例KML数据</name>
        <Placemark>
            <name>上海</name>
            <description>上海市</description>
            <Point>
                <coordinates>121.0,31.0,0</coordinates>
            </Point>
        </Placemark>
        <Placemark>
            <name>广州</name>
            <description>广州市</description>
            <Point>
                <coordinates>113.0,23.0,0</coordinates>
            </Point>
        </Placemark>
        <Placemark>
            <name>北京</name>
            <description>北京市</description>
            <Point>
                <coordinates>116.0,40.0,0</coordinates>
            </Point>
        </Placemark>
    </Document>
</kml>`;

        // 将KML字符串转换为Blob对象
        const blob = new Blob([kmlData], { type: 'application/vnd.google-earth.kml+xml' });
        const url = URL.createObjectURL(blob);

        // 加载KML数据源
        const dataSourcePromise = (window as any).Cesium.KmlDataSource.load(url, {
            camera: viewer.scene.camera,
            canvas: viewer.scene.canvas
        });

        dataSourcePromise.then((dataSource: any) => {
            viewer.dataSources.add(dataSource);
            addedDataSources.push(dataSource);
            dataSourceCount.value = addedDataSources.length;

            dataSourceStatus.value = '加载成功';
            dataSourceStatusClass.value = 'status-success';
            dataSourceCountClass.value = 'status-success';

            console.log('KML数据加载成功');
            
            // 清理临时URL
            URL.revokeObjectURL(url);
            
            // 飞行到KML数据范围
            viewer.flyTo(dataSource);
        }).catch((error: any) => {
            console.error('加载KML数据失败:', error);
            dataSourceStatus.value = '加载失败';
            dataSourceStatusClass.value = 'status-error';
            
            // 清理临时URL
            URL.revokeObjectURL(url);
        });

    } catch (error) {
        console.error('创建KML数据失败:', error);
        dataSourceStatus.value = '加载失败';
        dataSourceStatusClass.value = 'status-error';
    }
};

// 加载3D模型
const load3DModel = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        return;
    }

    try {
        dataSourceStatus.value = '加载中...';
        dataSourceStatusClass.value = 'status-loading';

        // 创建3D模型实体
        const entity = viewer.entities.add({
            name: "3D模型",
            position: (window as any).Cesium.Cartesian3.fromDegrees(118.30712, 32.30607, 0),
            model: {
                uri: "./assets/custom/cube.glb", //加载glb模型
                scale: 2, // 模型本身大小
                minimumPixelSize: 128, // 最小的模型像素
                maximumScale: 20000, // 最大的模型像素
                runAnimations: true, // 是否显示动画
                clampAnimations: true, // 是否保持最后一帧的动画
                color: (window as any).Cesium.Color.RED, // 模型加颜色
                colorBlendMode: (window as any).Cesium.ColorBlendMode.MIX, // 用于设置模型和颜色的关系
                colorBlendAmount: 0.5 // 这个属性必须是 MIX 混合属性才能生效
            },
            show: true // 是否显示或隐藏
        });

        // 设置摄像头定位到模型处
        viewer.trackedEntity = entity;

        dataSourceStatus.value = '加载成功';
        dataSourceStatusClass.value = 'status-success';
        dataSourceCount.value = addedDataSources.length + 1;
        dataSourceCountClass.value = 'status-success';

        console.log('3D模型加载成功');
    } catch (error) {
        console.error('加载3D模型失败:', error);
        dataSourceStatus.value = '加载失败';
        dataSourceStatusClass.value = 'status-error';
    }
};

// 添加标签
const addLabels = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        return;
    }

    try {
        dataSourceStatus.value = '加载中...';
        dataSourceStatusClass.value = 'status-loading';

        // 创建文本标签
        const textLabel = viewer.entities.add({
            position: (window as any).Cesium.Cartesian3.fromDegrees(116.0, 40.0),
            label: {
                text: "北京",
                font: "14pt sans-serif",
                fillColor: (window as any).Cesium.Color.WHITE,
                outlineColor: (window as any).Cesium.Color.BLACK,
                outlineWidth: 2,
                style: (window as any).Cesium.LabelStyle.FILL_AND_OUTLINE,
                pixelOffset: new (window as any).Cesium.Cartesian2(0, -9),
                horizontalOrigin: (window as any).Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: (window as any).Cesium.VerticalOrigin.BOTTOM
            }
        });

        // 创建图形标签
        const billboard = viewer.entities.add({
            position: (window as any).Cesium.Cartesian3.fromDegrees(121.0, 31.0),
            billboard: {
                image: "",
                scale: 0.5,
                horizontalOrigin: (window as any).Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: (window as any).Cesium.VerticalOrigin.BOTTOM
            }
        });

        dataSourceStatus.value = '加载成功';
        dataSourceStatusClass.value = 'status-success';
        dataSourceCount.value = addedDataSources.length + 2;
        dataSourceCountClass.value = 'status-success';

        console.log('标签添加成功');
    } catch (error) {
        console.error('添加标签失败:', error);
        dataSourceStatus.value = '加载失败';
        dataSourceStatusClass.value = 'status-error';
    }
};

// 创建几何形体
const createGeometry = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        return;
    }

    try {
        dataSourceStatus.value = '加载中...';
        dataSourceStatusClass.value = 'status-loading';

        // 创建点要素
        const point = viewer.entities.add({
            position: (window as any).Cesium.Cartesian3.fromDegrees(116.0, 40.0),
            point: {
                pixelSize: 10,
                color: (window as any).Cesium.Color.YELLOW
            }
        });

        // 创建线要素
        const polyline = viewer.entities.add({
            polyline: {
                positions: (window as any).Cesium.Cartesian3.fromDegreesArray([
                    116.0, 40.0,
                    121.0, 31.0,
                    113.0, 23.0
                ]),
                width: 5,
                material: (window as any).Cesium.Color.ORANGE,
                clampToGround: true
            }
        });

        // 创建面要素
        const polygon = viewer.entities.add({
            polygon: {
                hierarchy: (window as any).Cesium.Cartesian3.fromDegreesArray([
                    118.0, 32.0,
                    119.0, 32.0,
                    119.0, 33.0,
                    118.0, 33.0
                ]),
                material: (window as any).Cesium.Color.PURPLE.withAlpha(0.6),
                outline: true,
                outlineColor: (window as any).Cesium.Color.MAGENTA
            }
        });

        // 创建体要素
        const box = viewer.entities.add({
            position: (window as any).Cesium.Cartesian3.fromDegrees(104.0, 30.0),
            box: {
                dimensions: new (window as any).Cesium.Cartesian3(200000.0, 200000.0, 200000.0),
                material: (window as any).Cesium.Color.CYAN.withAlpha(0.7),
                outline: true,
                outlineColor: (window as any).Cesium.Color.BLACK
            }
        });

        dataSourceStatus.value = '加载成功';
        dataSourceStatusClass.value = 'status-success';
        dataSourceCount.value = addedDataSources.length + 4;
        dataSourceCountClass.value = 'status-success';

        console.log('几何形体创建成功');
    } catch (error) {
        console.error('创建几何形体失败:', error);
        dataSourceStatus.value = '加载失败';
        dataSourceStatusClass.value = 'status-error';
    }
};

// 清除空间数据
const clearSpatialData = () => {
    const viewer = getCesiumViewer();
    if (!viewer) {
        console.error('Cesium Viewer不可用');
        return;
    }

    try {
        // 清除所有数据源
        addedDataSources.forEach(dataSource => {
            viewer.dataSources.remove(dataSource);
        });
        addedDataSources = [];

        // 清除所有实体
        viewer.entities.removeAll();

        dataSourceStatus.value = '已清除';
        dataSourceStatusClass.value = 'status-cleared';
        dataSourceCount.value = 0;
        dataSourceCountClass.value = 'status-cleared';

        console.log('空间数据已清除');
    } catch (error) {
        console.error('清除空间数据失败:', error);
    }
};

onMounted(() => {
    // 组件加载时检查Viewer状态
    const viewer = getCesiumViewer();
    if (viewer) {
        dataSourceStatus.value = '就绪';
        dataSourceStatusClass.value = 'status-ready';
        dataSourceCount.value = 0;
        dataSourceCountClass.value = 'status-ready';
    } else {
        dataSourceStatus.value = 'Viewer不可用';
        dataSourceStatusClass.value = 'status-error';
        dataSourceCount.value = 0;
        dataSourceCountClass.value = 'status-error';
    }
});
</script>

<style scoped>
.spatial-data-loader {
    width: 280px;
    box-sizing: border-box;
    padding: 10px;
}

.spatial-info {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    margin-bottom: 15px;
    font-size: 14px;
}

.spatial-controls {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 15px;
}

.spatial-btn, .clear-btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    width: 100%;
}

.spatial-btn {
    background-color: #4CAF50;
    color: white;
}

.spatial-btn:hover {
    background-color: #45a049;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #da190b;
}

.spatial-details {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    margin-bottom: 15px;
    font-size: 14px;
    overflow: auto;
}

.spatial-status {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    border-left: 4px solid #dee2e6;
    font-size: 14px;
}

.status-unknown {
    color: #6c757d;
}

.status-ready {
    color: #17a2b8;
    font-weight: bold;
}

.status-loading {
    color: #ffc107;
    font-weight: bold;
}

.status-success {
    color: #28a745;
    font-weight: bold;
}

.status-error {
    color: #dc3545;
    font-weight: bold;
}

.status-cleared {
    color: #6c757d;
    font-weight: bold;
}
</style>
